# -*- coding: utf-8 -*-
import re, string, sys
import mechanize
from BeautifulSoup import BeautifulSoup

url_host = "http://localhost:8080"
url_app = "%s/projectmgr/control" % url_host
filename='test-td-timesheet.xls'

import pprint
pp = pprint.PrettyPrinter(indent=2)

def applyDict2Form(_br, _form_name, _dict): 
    _br.select_form(name=_form_name)
    f = _br.form
    for kk in _dict: 
        if type(_dict[kk]) is unicode: v = _dict[kk].encode('utf-8')
        elif not _dict.has_key(kk) or _dict[kk] is None: v = ''
        else: v=_dict[kk]
        c=f.find_control(name=kk)
        if c.__class__.__name__=='SelectControl': f[kk]=v and [v] or []
        elif c.__class__.__name__=='HiddenControl': c._value=v
        else: f[kk]=v

def page_get_id_and_soup(page):
    soup = BeautifulSoup(page, convertEntities=BeautifulSoup.HTML_ENTITIES)
    title = soup.find('div', {'class':'page-title'}) # ok
    id = None
    if title: 
        m = re.search(r'\[([^\]]+)\]', title.find('span').getText())
        if m: id = m.groups()[0]
    print "---> new id %s" % id
    return (id, soup)

def page_get_h1_id_and_soup(page):
    soup = BeautifulSoup(page, convertEntities=BeautifulSoup.HTML_ENTITIES)
    title = soup.find('h1') # ok
    id = None
    if title: 
        m = re.search(r' (\d+) ', title.getText())
        if m: id = m.groups()[0]
    print "---> new id %s" % id
    return (id, soup)


def page_soup_error(soup):
    cm = soup.find('div', {'id':'content-messages'}) # error
    if cm:
        print cm.getText()
        return True
    return False

def page_get_error(page):
    soup = BeautifulSoup(page, convertEntities=BeautifulSoup.HTML_ENTITIES)
    return page_soup_error(soup)

br = mechanize.Browser()

# login
br.open("%s/login" % url_app)
br.select_form(name="loginform")
br.form['USERNAME']='admin'
br.form['PASSWORD']='ofbiz'
res = br.submit()

mcc = { '_':['master','tasks'],
     'master':{
         'id':['A^1',u'時間表ID'],
         'party':['A^2',u'成員'],
         'date':['A^3',u'日期'],
     },
     'tasks':{
         '*':{
             'id':['A1',u'任務ID'],
             'name':['B1',u'名稱'],
             'done':['C1',u'完成'],
             '1':['D1',u'週一'],
             '2':['E1',u'週二'],
             '3':['F1',u'週三'],
             '4':['G1',u'週四'],
             '5':['H1',u'週五'],
             '6':['I1',u'週六'],
             '7':['J1',u'週日'],
         },
     },
}
from tabledown.tdxls import TDXls
tdx = TDXls(mcc)
data = tdx.xls2dict(filename)
#pp.pprint(data)

sheet1=data['Sheet1']

master=sheet1['master']
tasks=sheet1['tasks']

master_keys = ('id','party','date')
task_keys = ('id','name','done')
wday_keys = ('1','2','3','4','5','6','7')

write_file = False

mId, mParty, mDate = map(master.get, master_keys)
print "<<<", mId, mParty, mDate

# check existed of timesheet

br.open("%s/addWeeklyTimesheet" % url_app)
br.select_form(name='AddWeeklyTimesheet')
br.form['partyId']=[mParty]
br.form['requiredDate']=mDate
res=br.submit()
id, soup = page_get_h1_id_and_soup(res.get_data())
master['id']=id
if page_soup_error(soup): sys.exit(1)

#br.open("http://localhost:8080/projectmgr/control/Timesheet?timesheetId=10064")

wc_lst=[]
def getEditWeekTimesheet():
    while wc_lst: wc_lst.pop()
    br.select_form(name='EditWeekTimesheet')
    for c in br.form.controls: 
        if c.__class__.__name__=='SelectControl' and c.name.find('workEffortId')>=0 and c.pairs()[0][1]=='': 
            # c.pairs() ex. [('workEffortId_o_0', '10234')]
            wc_lst.append(c)

getEditWeekTimesheet() # initial form

loop_cnt=0 # each 3 entres need submit
dEntry={}
for task in tasks:
    # time entries
    eId, eName, eDone = map(task.get, task_keys)
    eTime = map(task.get, wday_keys)
    print "<<<", eId, eName, eDone, string.join(eTime,':')

    if eId:
        sel_name=wc_lst[loop_cnt].name
        sel_id=sel_name[sel_name.rfind('_')+1:]
        try:
            br.form[sel_name]=[eId]
        except:
            print " ! Task(%s) can't use, %s skiped!" % (eId, eName)
        dEntry[sel_name]=eId
        if eDone in ['Y','y', 'X', 'x']:
            dEntry['checkComplete_o_'+sel_id]=['Y']
        for d in range(0,7):
            day_name="hoursDay%d_o_%s" % (d, sel_id)
            dEntry[day_name]=eTime[d]
        loop_cnt+=1
        if loop_cnt==3:
            applyDict2Form(br, 'EditWeekTimesheet', dEntry)
            res=br.submit()
            if page_get_error(res.get_data()): sys.exit(1)
            getEditWeekTimesheet() # reset form
            loop_cnt=0
            dEntry.clear()
    
if loop_cnt!=0:
    print "another %d records" % loop_cnt
    applyDict2Form(br, 'EditWeekTimesheet', dEntry)
    res=br.submit()
    if page_get_error(res.get_data()): sys.exit(1)

tdx.dict2xls(data['Sheet1'],re.sub(".xls", "-output.xls", filename))

